﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using Kawanon.Localization;
using System.IO;
using Microsoft.Win32;

namespace Kawanon.QtHoney
{
	public partial class LanguageView : UserControl
	{
		private const string DialogFilter = "Language File (*.xml)|*.xml";

		private Dictionary<string, string> m_resources = new Dictionary<string, string>();
		private int m_suspendCount = 0;
		private ScrollEffect m_effect;

		public LanguageView()
		{
			InitializeComponent();

			m_effect = new ScrollEffect(panelReboot);
			m_effect.Interval = 15;
			m_effect.Frame = 20;
		}

		private bool IsSuspended()
		{
			return m_suspendCount > 0;
		}

		private void InitResources()
		{
			Assembly asm = Assembly.GetExecutingAssembly();
			string[] names = asm.GetManifestResourceNames();
			foreach (string name in names)
			{
				if (!name.EndsWith(".xml"))
				{
					continue;
				}
				if (name.IndexOf("lang.") == -1)
				{
					continue;
				}

				StringResource res = StringResource.From(asm.GetManifestResourceStream(name));
				string lang = res["Language"].GetText(true);
				if (lang == null)
				{
					continue;
				}

				m_resources[lang] = name;
				checkedListBox1.Items.Add(lang);
			}
		}

		private void LanguageView_Load(object sender, EventArgs e)
		{
			StringResource.Apply("LanguageView_Text",
				labelPath, labelResources, textBoxExportDescription, buttonExport, labelCaution);

			pictureBox1.Image = new Bitmap(SystemIcons.Warning.ToBitmap(), pictureBox1.Size);

			InitResources();

			m_suspendCount++;

			string path = Plugins.GetLanguageResourcePath();
			textBoxPath.Text = path;

			string resName = StringResource.ToResourceName(path);
			if (resName != null)
			{
				string lang = StringResource.Default["Language"].Text;
				int index = checkedListBox1.Items.IndexOf(lang);
				checkedListBox1.SetItemChecked(index, true);
			}
			m_suspendCount--;
		}

		private void ClearChecked()
		{
			m_suspendCount++;
			foreach (int i in checkedListBox1.CheckedIndices)
			{
				checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
			}
			m_suspendCount--;
		}

		private void ChooseResource(string path, bool embedded)
		{
			if (embedded)
			{
				textBoxPath.Text = StringResource.ToInternalPath(path);
			}
			else
			{
				textBoxPath.Text = path;
			}
		}

		private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
		{
			if (IsSuspended())
			{
				return;
			}

			// キーボード操作の場合に不都合があるかも
			/*
			int index = checkedListBox1.IndexFromPoint(checkedListBox1.PointToClient(Cursor.Position));
			if (index == -1)
			{
				// アイテム外のクリックは無視
				e.NewValue = e.CurrentValue;
				return;
			}
			*/

			if (e.NewValue == CheckState.Unchecked && checkedListBox1.CheckedIndices.Count == 1)
			{
				e.NewValue = e.CurrentValue;
				return;
			}

			ClearChecked();

			string lang = (string)checkedListBox1.Items[e.Index];
			ChooseResource(m_resources[lang], true);
		}

		private void buttonBrowse_Click(object sender, EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = DialogFilter;

			if (dlg.ShowDialog() != DialogResult.OK)
			{
				return;
			}

			ClearChecked();
			ChooseResource(dlg.FileName, false);
		}

		private void buttonExport_Click(object sender, EventArgs e)
		{
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.Filter = DialogFilter;
			dlg.FileName = "QTHoney.lang.xxx.xml";

			if (dlg.ShowDialog() != DialogResult.OK)
			{
				return;
			}

			string lang = (string)checkedListBox1.SelectedItem;
			string name = m_resources[lang];

			Assembly asm = Assembly.GetExecutingAssembly();
			Stream stm = asm.GetManifestResourceStream(name);
			byte[] data = new byte[stm.Length];
			if (stm.Read(data, 0, data.Length) != data.Length)
			{
				throw new Exception("Embedded resource stream load error");
			}
			stm.Close();
			File.WriteAllBytes(dlg.FileName, data);
		}

		private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			bool b = (checkedListBox1.SelectedIndices.Count == 1);

			buttonExport.Enabled = b;
			textBoxExportDescription.Enabled = b;
		}

		public void Save()
		{
			if (!IsHandleCreated)
			{
				return;
			}

			RegistryKey reg = Plugins.OpenRegistryKey(true);
			reg.SetValue("Language", textBoxPath.Text);
			reg.Close();
		}

		private void textBoxPath_TextChanged(object sender, EventArgs e)
		{
			if (IsSuspended())
			{
				return;
			}

			checkedListBox1.ClearSelected();

			if (!m_effect.Visible)
			{
				m_effect.SetVisible(true);
			}
		}
	}
}
